package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Name CategoryServiceImpl
 * @Author stella
 * @Date 2023-03-02 12:11 PM
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    //分类列表
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }
    @Autowired
    private HttpSession httpSession;
    //新增分类
    @Override
    public void save(Category c) {
        long id = IdUtil.getSnowflake(1, 1).nextId();
        c.setId(id);
//        c.setCreateTime(new Date());
//        c.setUpdateTime(new Date());
//        Employee e = (Employee)httpSession.getAttribute(Constant.SESSION_EMPLOYEE);
//        c.setCreateUser(e.getId());
//        c.setUpdateUser(e.getId());
        categoryMapper.save(c);
    }

    //修改分类
    @Override
    public void update(Category c) {
//        Employee e = (Employee)httpSession.getAttribute(Constant.SESSION_EMPLOYEE);
//        c.setUpdateUser(e.getId());
//        c.setUpdateTime(new Date());
        categoryMapper.updateById(c);
    }

    //删除分类
    @Override
    public ResultInfo delete(Long id) {
        // 1- 根据分类id查询菜品数量
        Integer dishCount = categoryMapper.countDishByCategoryId(id);
        if (dishCount > 0 ){
            //return ResultInfo.error("该分类下有菜品，不允许删除");
            throw new CustomException("该分类下有菜品，不允许删除");
        }
        // 2- 根据分类id查询套餐的数量
        Integer SetmealCount = categoryMapper.countSetmealByCategoryId(id);
        if ( SetmealCount > 0 ){
            //return ResultInfo.error("该分类下有套餐，不允许删除");
            throw new CustomException("该分类下有套餐，不允许删除");
        }

        // 3- 根据id删除分类
        categoryMapper.delete(id);
        return ResultInfo.success();
    }

    // 新增菜品/套餐时查询的分类信息
    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType,type);// 根据类型  type= 1
        qw.orderByAsc(Category::getSort); // 分类升序 order by sort asc
        List<Category> categories = categoryMapper.selectList(qw);
        return categories;
    }
}
